package com.zyx.nettypro.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author zyx
 * @since 2021/9/19 15:20
 */
public class FileChannelReadAndWrite {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("input/netty/file01.txt");
        FileChannel fileChannelFrom = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("2.input/netty/file02.txt");
        FileChannel fileChannelTo = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (true) {
            //这里有一个重要的操作，一定不要忘了
            /*
             public final Buffer clear() {
                position = 0;
                limit = capacity;
                mark = -1;
                return this;
            }
             */
            // 清空buffer
            byteBuffer.clear();
            int read = fileChannelFrom.read(byteBuffer);
            System.out.println("read =" + read);
            // read = -1表示读完
            if(read == -1) {
                break;
            }
            // 将buffer 中的数据写入到 fileChannel02 -- 2.txt
            byteBuffer.flip();
            fileChannelTo.write(byteBuffer);
        }

        // 关闭相关的流
        fileInputStream.close();
        fileOutputStream.close();
    }
}
